package com.huidu.bitrade.utils;

import com.huidu.bitrade.service.LocaleMessageSourceService;
import com.huidu.bitrade.util.MessageResult;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import org.springframework.web.client.RestTemplate;

import java.math.BigDecimal;

@Component
@Slf4j
public class RpcServerUtil {
    @Autowired
    private RestTemplate restTemplate;
    @Autowired
    private LocaleMessageSourceService messageSource;

    public BigDecimal getRPCWalletBalance(String url, String unit) {
        if(StringUtils.isEmpty(url) || (StringUtils.hasText(url) && url.contains("http://SERVICE-RPC-"))){
            log.info("===================RPC服务不存在返回默认值=======================");
            return BigDecimal.ZERO;
        }
        try {
            ResponseEntity<MessageResult> result = restTemplate.getForEntity(url, MessageResult.class);
            log.info("result={}", result);
            if (result.getStatusCode().value() == 200) {
                MessageResult mr = result.getBody();
                if (mr.getCode() == 0) {
                    String balance = mr.getData().toString();
                    BigDecimal bigDecimal = new BigDecimal(balance);
                    log.info(unit + "(" + url + ")" + messageSource.getMessage("HOT_WALLET_BALANCE"), bigDecimal);
                    return bigDecimal;
                }
            }
        } catch (IllegalStateException e) {
            log.error("error={}", e);
            return new BigDecimal("0");
        } catch (Exception e) {
            log.error("error={}", e);
            return new BigDecimal("0");
        }
        return new BigDecimal("0");
    }

    public Long getRPCBlockHeight(String url, String unit) {
        if(StringUtils.isEmpty(url) || (StringUtils.hasText(url) && url.contains("http://SERVICE-RPC-"))){
            log.info("===================RPC服务不存在返回默认值=======================");
            return 0L;
        }
        try {
            ResponseEntity<MessageResult> result = restTemplate.getForEntity(url, MessageResult.class);
            log.info("result={}", result);
            if (result.getStatusCode().value() == 200) {
                MessageResult mr = result.getBody();
                if (mr.getCode() == 0) {
                    String height = mr.getData().toString();
                    Long longHeight = Long.valueOf(height);
                    return longHeight;
                }
            }
        } catch (IllegalStateException e) {
            log.error("error={}", e);
            return Long.valueOf(0);
        } catch (Exception e) {
            log.error("error={}", e);
            return Long.valueOf(0);
        }
        return Long.valueOf(0);
    }
}
